package org.teziyou.ticket.render;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;

import org.teziyou.ticket.constant.CommonConstant;

import com.github.napp.kaptcha.Kaptcha;
import com.github.napp.kaptcha.KaptchaTextCreator;
import com.jfinal.kit.EncryptionKit;
import com.jfinal.render.Render;

public class KCaptchaRender extends Render {

	@Override
	public void render() {
		String vCode = KaptchaTextCreator.getText(4);
		BufferedImage bi = new Kaptcha().createImage(vCode);
		ServletOutputStream out = null;
		try {
			vCode = EncryptionKit.md5Encrypt(vCode);
			Cookie cookie = new Cookie(CommonConstant.comment_captcha_key, vCode);
			cookie.setMaxAge(-1);
			cookie.setPath("/");
			response.addCookie(cookie);
			response.setHeader("Pragma","no-cache");
	        response.setHeader("Cache-Control","no-cache");
	        response.setDateHeader("Expires", 0);
	        response.setContentType("image/jpeg");
			out = response.getOutputStream();  
			// write the data out  
			ImageIO.write(bi, "jpg", out);  
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(out!=null)
					out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
